package com.ly.hotel.view.userLogin;

import java.io.File;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.ly.hotel.R;
import com.ly.hotel.common.Constants;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.msgevent.CloseHandEvent;
import com.ly.hotel.service.SPAService;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.view.InitActivity;
import com.ly.hotel.view.floatWindows.ShuaKaFloatWin;

import de.greenrobot.event.EventBus;

public class UserLoginActivity extends AlertDialog {

	private ImageView tipsImage;
	private Animation alphaAnimation;

	MyHandler mHandler = new MyHandler();
	private Context context;
	private boolean threadFlag = true;
	
	public UserLoginActivity(Context context, int theme) {
		super(context, theme);
		this.context = context;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_user_login);
		EventBus.getDefault().register(this);
		initView();
	}

	@Override
	protected void onStart() {
		super.onStart();

		new Thread() {
			public void run() {
				MyApplication.clearBandNo();
				while (MyApplication.getBandNo() == "" && threadFlag) {
					try {
						Thread.sleep(100); 
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} 
				
				InitActivity.stopService(context, "ShuaKaFloatWin", ShuaKaFloatWin.class);
				
				Message message = new Message();
				message.what = 1;
				mHandler.sendMessage(message);
				Log.e("inputHand", "InputHandNoActivity->set Text to HandNo");
			}
		}.start();

	}

	private void initView() {
		tipsImage = findViewById(R.id.liuwei_tips);
		alphaAnimation = AnimationUtils.loadAnimation(context, R.anim.alpha_anim);
		tipsImage.startAnimation(alphaAnimation);

		Intent inteservice = new Intent(context, ShuaKaFloatWin.class);
		context.startService(inteservice);

		if (MyApplication.getSeatBitmap() != null) {
			tipsImage.setBackgroundDrawable(new BitmapDrawable(MyApplication.getSeatBitmap()));
		} else {
			File ff = new File(Constants.SEAT_FILE_PATH);
			if (ff.exists()) {
				Bitmap logoImage = BitmapFactory.decodeFile(Constants.SEAT_FILE_PATH);
				if (logoImage != null) {
					tipsImage.setBackgroundDrawable(new BitmapDrawable(logoImage));
					MyApplication.setSeatBitmap(logoImage);
					logoImage = null;
				}
			}else{
				tipsImage.setBackgroundResource(R.drawable.shuaka_tips);
			}
		}
	}

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	// TODO Auto-generated method stub
    	if(keyCode == KeyEvent.KEYCODE_BACK){
    		return true;
    	} else {
    		return super.onKeyDown(keyCode, event);
    	}
    }
    
	public void onEventMainThread(CloseHandEvent e) {
		this.dismiss();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		threadFlag = false; //退出没有介绍的线程
		EventBus.getDefault().unregister(this);
		super.onStop();
	}

	private void updateLogin(final String id) {
		new Thread() {
			@Override
			public void run() {
				try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/get-my-space.json?mac="
							+ MyApplication.getMAC() + "&key=massage";
					String rv = SPAService.myHttpPostMsg(url);
					Log.i("inputHand", "获取成功.rv=" + rv);
					//查找是否存在，存在就删掉，不存在就直接插入
					JSONObject jo;
					if(rv != null && !rv.equals("")){
						jo = new JSONObject(rv);
					} else {
						jo = new JSONObject();
					}
					
					java.text.DateFormat format1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
			        String info = MyApplication.getDeviceInfo()
							.getCategoryName() + "-" + MyApplication.getDeviceInfo().getName() + "#" + //"%23"就是#号
							format1.format(MyApplication.getDeviceInfo().getNow());

			        jo.put(id, info);
			        
			        String url1 = MyApplication.getHost() + SPAService.PROJECT + "/api/put-my-space.json?mac="
							+ MyApplication.getMAC() + "&key=massage&value=" + URLEncoder.encode(jo.toString());
			        Log.i("inputHand", "提交链接=>" + url1);
			        
					String rv1 = SPAService.myHttpPostMsg(url1);
					Log.i("inputHand", "结果=>" + rv1);
					
				} catch (HttpRequestFailException e) {
					Log.e("inputHand", e.getMessage());
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				// 更新本页面文本框显示读取到的卡号
				if(MyApplication.getBandNo().equals("")){
					if(this != null)
						dismiss();
					return;
				}
				Log.e("inputHand", "发送消息弹出挂机页面.");

				updateLogin(MyApplication.getBandNo());
				
				MyApplication.clearBandNo();
				
				try{
					if(this != null)
						tipsImage.clearAnimation();
						dismiss();
				}catch (Exception e) {
					Log.e("inputHand", "隐藏刷卡界面失败.");
				}
				break;
			}
		}
	};
}
